const std = @import("std");
const glfw = @import("zglfw");
const zopengl = @import("zopengl");
const zgui = @import("zgui");

pub var window: *glfw.Window = undefined;

pub fn init(allocator: std.mem.Allocator, loadopengl: anytype) !void {
    window = try glfw.Window.create(600, 600, "zig-gamedev: minimal_glfw_gl", null);
    window.setSizeLimits(400, 400, -1, -1);

    glfw.makeContextCurrent(window);

    glfw.swapInterval(1);
    try loadopengl();
    // try zopengl.loadCoreProfile(glfw.getProcAddress, 4, 0);
    // try zopengl.loadEsProfile(glfw.getProcAddress, 2, 0);

    // var gpa_state = std.heap.GeneralPurposeAllocator(.{}){};
    // defer _ = gpa_state.deinit();
    // const gpa = gpa_state.allocator();
    // _ = allocator;
    zgui.init(allocator);
    // defer zgui.deinit();

    const scale_factor = scale_factor: {
        const scale = window.getContentScale();
        break :scale_factor @max(scale[0], scale[1]);
    };
    // _ = zgui.io.addFontFromFile(
    //     "minimal_zgui_glfw_gl_content/" ++ "Roboto-Medium.ttf",
    //     std.math.floor(16.0 * scale_factor),
    // );
    zgui.getStyle().scaleAllSizes(scale_factor);

    zgui.backend.init(window);
}

pub fn deinit(allocator: std.mem.Allocator) void {
    window.destroy();
    _ = allocator;
    // defer zgui.deinit(allocator);
    // defer zgui.backend.deinit();
}

pub fn updateAndRender() void {
    glfw.pollEvents();

    const gl = zopengl.bindings;
    // gl.clearBufferfv(gl.COLOR, 0, &[_]f32{ 0, 0, 0, 1.0 });

    gl.clearColor(0.12, 0.24, 0.36, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);

    const fb_size = window.getFramebufferSize();
    zgui.backend.newFrame(@intCast(fb_size[0]), @intCast(fb_size[1]));

    // Set the starting window position and size to custom values
    zgui.setNextWindowPos(.{ .x = 20.0, .y = 20.0, .cond = .first_use_ever });
    zgui.setNextWindowSize(.{ .w = -1.0, .h = -1.0, .cond = .first_use_ever });

    if (zgui.begin("My window", .{})) {
        if (zgui.button("Press me!", .{ .w = 200.0 })) {
            // std.debug.print("Button pressed\n", .{});
        }
    }
    zgui.end();
    zgui.backend.draw();
    window.swapBuffers();
}
